<template>
  <div class="box">
    <div class="box-top">
      <div class="box-top-con">
        <img src="@/assets/img/home/logo.png" alt="" />
        <p>青海无人机综合管理服务平台</p>
      </div>
    </div>
    <div class="main">
      <div class="main-con">
        <div class="main-con-img">
          <img src="@/assets/img/register/icon_success.png" alt="" />
        </div>
        <p class="main-con-title">单位登录成功！</p>

        <p class="main-con-bind">
          若想继续浏览平台，请使用手机号登录。
          <span @click="clickBind(1)">绑定单位管理员！</span>
        </p>
        <div class="main-con-btn" @click="clickLogin">手机号登录</div>
        <div class="main-con-line"></div>
        <p class="main-con-title2">绑定单位管理员</p>
        <p class="main-con-title3">每个单位最多绑定三个单位管理员</p>
        <div class="main-con-operation">
          <p @click="unbindAdmin">解除单位管理员绑定</p>
          <span></span>
          <p @click="changePassword">更改单位密码</p>
        </div>
        <div class="main-con-list">
          <div class="main-con-list-item" v-for="(item, index) in adminList" :key="index">
            <!-- 已绑定 -->
            <div class="main-con-list-item-bound">
              <div class="main-con-list-item-img"></div>
              <div class="main-con-list-item-text">
                <p style="color: #3369f4">{{ item.mobile }}</p>
                <p>
                  {{ item.name }}
                </p>
              </div>
              <div class="main-con-list-item-bound-delete" @click="clickUnbind(item, index)" v-if="unbindState">
                <img src="@/assets/img/companyLogin/delete.png" alt="" />
              </div>
            </div>
          </div>
          <!-- 未绑定管理员 -->
          <div class="main-con-list-item" v-for="(item, index) in unboundList" :key="index">
            <div class="main-con-list-unbound" :class="{active: isActive === index}" v-if="adminList.length < 3">
              <div class="main-con-list-item-img"></div>
              <div class="main-con-list-item-text" @click="clickBind(index)">
                <p style="color: #666666; margin: 0">单位管理员</p>
                <p style="color: #1383fb; cursor: pointer; margin: 0">去绑定</p>
              </div>
            </div>
          </div>
        </div>
        <!-- 平台内绑定 -->
        <el-dialog v-model="insideVisible" title="绑定单位管理员" width="30%" :before-close="insideCancel">
          <div class="dialog-line"></div>
          <div class="dialog">
            <div class="dialog-left">
              <div class="dialog-left-search">
                <el-input v-model.trim="companySearch" placeholder="请输入账号名称" maxLength="40"> </el-input>
                <div class="btn-search" type="primary" @click="searchCompanyUser">搜索</div>
              </div>
              <div>
                <div class="dialog-left-list" v-for="(item, index) in checkedSearch" :key="index">
                  <span>{{ item.name }}</span
                  ><el-icon @click="handleClose(index)"><Close /></el-icon>
                </div>
              </div>
              <div class="dialog-left-footer">
                <el-button class="btn-cancel" @click="insideCancel">取消 </el-button>
                <el-button class="btn-confirm" type="primary" @click="insideConfirm">绑定</el-button>
              </div>
            </div>
            <div class="dialog-right">
              <p class="dialog-right-title">{{ unitInfo.unit_name }}</p>
              <div class="dialog-right-list">
                <el-checkbox-group v-model="checkedSearch" @change="handleCheckedCitiesChange">
                  <el-checkbox
                    v-for="(item, index) in companyUserList"
                    :key="index"
                    :label="item"
                    :disabled="item !== checkedSearch[0] && checkedSearch.length > 0"
                    >{{ item.name }}
                    <img v-if="item.role_id === 1" src="@/assets/img/device/icon_sup.png" alt="" />
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </el-dialog>
        <!-- 平台外绑定 -->
        <el-dialog v-model="outsideVisible" title="绑定单位管理员" width="22%" :before-close="insideCancel">
          <div style="height: 1px; background: rgba(0, 0, 0, 0.06)"></div>
          <el-form
            size="small"
            :model="formBind.form"
            :rules="formBind.rules"
            ref="formBindFrom"
            label-width="75px"
            style="padding: 0 32px"
          >
            <el-form-item label="账号" prop="mobile">
              <el-input v-model.trim="formBind.form.mobile" placeholder="请输入手机号" maxLength="40" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="账号名称" prop="name">
              <el-input v-model.trim="formBind.form.name" placeholder="请输入用户名" maxLength="40" clearable>
              </el-input>
            </el-form-item>
          </el-form>
          <div style="height: 1px; background: rgba(0, 0, 0, 0.06); margin-top: 30px"></div>
          <template #footer>
            <span>
              <el-button class="btn-cancel" @click="outsideCancel">取消</el-button>
              <el-button class="btn-confirm" type="primary" @click="outsideConfirm">绑定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
      <!-- 更改密码弹窗 -->
      <el-dialog v-model="passwordVisible" title="更改单位密码" width="22%" :before-close="clickPasswordCancel">
        <div class="dialog-line"></div>
        <el-form
          size="small"
          ref="formCompanyFrom"
          :rules="formCompany.rules"
          :model="formCompany.form"
          label-width="95px"
          style="padding: 0 42px"
        >
          <el-form-item label="密码" prop="oldPassword">
            <el-input
              v-model.trim="formCompany.form.oldPassword"
              placeholder="请输入当前密码"
              type="password"
              maxLength="40"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model.trim="formCompany.form.newPassword"
              placeholder="请输入新密码"
              type="password"
              maxLength="40"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="rePassword">
            <el-input
              v-model.trim="formCompany.form.rePassword"
              placeholder="请确认新密码"
              type="password"
              maxLength="40"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-line" style="margin-top: 30px"></div>
        <template #footer>
          <span>
            <el-button class="btn-cancel" @click="clickPasswordCancel">取消</el-button>
            <el-button class="btn-confirm" type="primary" @click="clickPasswordSure">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import type {Action} from 'element-plus';
import {useRouter} from 'vue-router';
import personalApi from '@/api/personalApi.ts';

const router = useRouter();

const adminList = ref([]);
const unboundList = ref([]);
const userId = ref('');
const companySearch = ref('');
const companyUserList = ref([]); // 单位人员列表
const unbindState = ref(false); // 解除绑定状态
const checkedSearch = ref([]); // 选中单个
const isActive = ref<Number>(); // 当前点击管理员下标
const insideVisible = ref(false); // 平台内绑定
const outsideVisible = ref(false); // 平台外绑定
const passwordVisible = ref(false); // 忘记密码弹窗
const formCompanyFrom = ref(null);
const formCompany = reactive({
  form: {oldPassword: '', newPassword: '', rePassword: ''},
  rules: {
    oldPassword: [{required: true, message: '请输入当前密码', trigger: 'blur'}],
    newPassword: [{required: true, message: '请输入新密码', trigger: 'blur'}],
    rePassword: [{required: true, message: '请确认新密码', trigger: 'blur'}],
  },
});
// 平台外绑定
const formBindFrom = ref(null);
const formBind = reactive({
  form: {name: '', mobile: ''},
  rules: {
    name: [{required: true, message: '请输入注册用户名称', trigger: 'blur'}],
    mobile: [{required: true, message: '请输入手机号', trigger: 'blur'}],
  },
});
const unitInfo = ref({}); // 单位信息

const clickLogin = () => {
  router.push({name: 'login', params: {activeName: 'personal'}});
};

// 解除绑定弹窗
const unbindAdmin = () => {
  unbindState.value = !unbindState.value;
};
// 更改密码弹窗
const changePassword = () => {
  passwordVisible.value = !passwordVisible.value;
};
// 更改密码确认取消
const clickPasswordSure = () => {
  formCompanyFrom.value.validate((valid) => {
    if (valid) {
      if (formCompany.form.newPassword !== formCompany.form.rePassword) {
        ElMessage.error('两次输入的新密码不一致');
        return;
      }
      personalApi
        .changeCompanyPassword({
          old_password: formCompany.form.oldPassword,
          new_password: formCompany.form.newPassword,
        })
        .then((res) => {
          ElMessage.success(res.message);
          formCompany.form = {
            oldPassword: '',
            newPassword: '',
            rePassword: '',
          };
          passwordVisible.value = !passwordVisible.value;
        })
        .catch((err) => {
          throw err;
        });
    }
  });
};
const clickPasswordCancel = () => {
  passwordVisible.value = !passwordVisible.value;
  formCompany.form = {oldPassword: '', newPassword: '', rePassword: ''};
};
// 点击绑定
const clickBind = (i) => {
  isActive.value = i;
  ElMessageBox.confirm('请问平台内人员绑定还是平台外人员绑定？', {
    distinguishCancelAndClose: true,
    type: 'warning',
    confirmButtonText: '平台内',
    cancelButtonText: '平台外',
  })
    .then(() => {
      insideVisible.value = !insideVisible.value;
      getCompanyUser();
      isActive.value = null;
    })
    .catch((action: Action) => {
      if (action === 'cancel') {
        outsideVisible.value = !outsideVisible.value;
      } else {
        isActive.value = null;
      }
    });
};
// 平台内绑定
const insideConfirm = () => {
  personalApi
    .addAdminUser({
      type: 2,
      user_id: userId.value,
    })
    .then((res) => {
      if (res.status === 0) {
        ElMessage.success(res.message);
        insideVisible.value = !insideVisible.value;
        isActive.value = null;
        getCompanyAdmin();
      }
    })
    .catch((err) => {
      throw err;
    });
};
const insideCancel = () => {
  companySearch.value = '';
  isActive.value = 0;
  checkedSearch.value = [];
  insideVisible.value = !insideVisible.value;
};
// 搜索单位人员
const searchCompanyUser = () => {
  personalApi
    .companyUserList({
      keyword: companySearch.value,
    })
    .then((res) => {
      if (res.data) {
        companyUserList.value = res.data;
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 选中单位人员
const handleCheckedCitiesChange = (val) => {
  userId.value = val[0].id;
};
// 删除已选中的人员
const handleClose = (index) => {
  checkedSearch.value.splice(index, 1);
};
// 平台外绑定
const outsideConfirm = () => {
  formBindFrom.value.validate((valid) => {
    if (valid) {
      personalApi
        .addAdminUser({
          type: 1,
          name: formBind.form.name,
          mobile: formBind.form.mobile,
        })
        .then((res) => {
          if (res.status === 0) {
            ElMessage.success(res.message);
            outsideVisible.value = !outsideVisible.value;
            isActive.value = null;
            getCompanyAdmin();
            unboundList.value.shift();
          }
        })
        .catch((err) => {
          throw err;
        });
    }
  });
};
const outsideCancel = () => {
  isActive.value = 0;
  formBind.form.name = '';
  formBind.form.mobile = '';
  outsideVisible.value = !outsideVisible.value;
};
// 点击解绑
const clickUnbind = (item, index) => {
  userId.value = adminList.value[index].id;
  ElMessageBox.confirm(`确定将${adminList.value[index].name}解除单位管理员绑定吗？解除后，该用户权限将变为普通用户。`, {
    distinguishCancelAndClose: true,
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(() => {
      personalApi
        .unbindAdmin({user_id: userId.value})
        .then((res) => {
          if (res.status === 0) {
            ElMessage.success(res.message);
            getCompanyAdmin();
          }
        })
        .catch((err) => {
          throw err;
        });
    })
    .catch((action: Action) => {});
};
// 获取单位人员列表
const getCompanyUser = () => {
  personalApi
    .companyUserList()
    .then((res) => {
      if (res.data) {
        companyUserList.value = res.data;
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 获取已绑定管理员列表
const getCompanyAdmin = () => {
  personalApi
    .companyUserList({role_id: '2'})
    .then((res) => {
      if (res.data) {
        adminList.value = res.data;
        unboundList.value = 3 - res.data.length;
      }
    })
    .catch((err) => {
      throw err;
    });
};
onMounted(() => {
  unitInfo.value = JSON.parse(localStorage.getItem('unit'));
  if (localStorage.getItem('unitToken')) {
    getCompanyAdmin();
  }
});
</script>
<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  &-top {
    height: 78px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: url(@/assets/img/home/bg.png);
    background-repeat: no-repeat;
    background-position: center center;
    &-con {
      display: flex;
      align-items: center;
      min-width: 300px;
      justify-content: center;
      margin-bottom: 15px;
      > img {
        width: 36px;
        height: 36px;
        margin-right: 14px;
      }
      > p {
        min-width: 200px;
        font-size: 24px;
        font-weight: bold;
        color: #ffffff;
        line-height: 31px;
      }
    }
  }
  .main {
    width: 100%;
    height: 93%;
    background: #f6f7f9;
    padding: 15px 30px 30px;
    box-sizing: border-box;
    &-con {
      width: 100%;
      height: 100%;
      overflow: hidden;
      background: #fff;
      &-img {
        width: 51px;
        height: 51px;
        margin: 0 auto;
        margin-top: 156px;
        > img {
          width: 100%;
          height: 100%;
        }
      }
      &-title {
        margin: 0;
        font-size: 20px;
        color: rgba(0, 0, 0, 0.85);
        height: 32px;
        line-height: 32px;
        margin-top: 24px;
        text-align: center;
      }
      &-bind {
        margin: 0;
        text-align: center;
        font-size: 14px;
        line-height: 32px;
        color: #838a9d;
        margin-top: 11px;
        > span {
          color: #1182fb;
          cursor: pointer;
        }
      }
      &-btn {
        width: 148px;
        height: 40px;
        background: #3369f4;
        border-radius: 4px;
        margin: 0 auto;
        text-align: center;
        line-height: 40px;
        color: #fff;
        margin-top: 26px;
        cursor: pointer;
      }
      &-line {
        width: 1440px;
        height: 1px;
        background: #d8d8d8;
        margin: 0 auto;
        margin-top: 47px;
      }
      &-title2 {
        height: 32px;
        font-size: 20px;
        color: rgba(0, 0, 0, 0.85);
        line-height: 32px;
        margin: 0;
        text-align: center;
        margin-top: 63px;
      }
      &-title3 {
        height: 32px;
        font-size: 14px;
        color: #838a9d;
        line-height: 32px;
        margin: 0;
        text-align: center;
        margin-top: 5px;
      }
      &-operation {
        display: flex;
        justify-content: center;
        align-items: center;
        > p {
          font-size: 14px;
          color: #1182fb;
          cursor: pointer;
        }
        > span {
          display: block;
          width: 1px;
          height: 12px;
          background: #d8d8d8;
          margin: 0 23px;
        }
      }
      &-list {
        display: flex;
        justify-content: center;
        margin-top: 30px;
        &-item {
          margin-right: 32px;
          &-img {
            width: 29px;
            height: 29px;
            margin-right: 14px;
            background: url(@/assets/img/companyLogin/icon_1.png);
            background-repeat: no-repeat;
            background-size: 100%;
          }
          p {
            margin: 0;
          }
          &-text {
            > p:nth-of-type(2) {
              color: #3369f4;
              font-weight: bold;
              margin-top: 2px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          &-bound {
            width: 200px;
            height: 66px;
            display: flex;
            align-items: center;
            background: #ebeffa;
            border-radius: 2px;
            border: 2px dashed #3369f4;
            padding: 19px;
            box-sizing: border-box;
            position: relative;
            .main-con-list-item-img {
              background: url(@/assets/img/companyLogin/icon_3.png);
              background-repeat: no-repeat;
              background-size: 100%;
            }
            &-delete {
              position: absolute;
              top: 5px;
              right: 5px;
              width: 20px;
              height: 20px;
              cursor: pointer;
              > img {
                width: 100%;
                height: 100%;
              }
            }
          }
        }
        &-unbound {
          width: 200px;
          height: 66px;
          display: flex;
          align-items: center;
          background: #ebeffa;
          border-radius: 2px;
          border: 2px dashed #666;
          padding: 19px;
          box-sizing: border-box;
          position: relative;
          p {
            &:nth-of-type(2) {
              font-weight: bold;
            }
          }
        }
        .active {
          background: #3369f4;
          border: 0;
          border-radius: 2px;
          .main-con-list-item-img {
            background: url(@/assets/img/companyLogin/icon_2.png);
            background-repeat: no-repeat;
            background-size: 100%;
          }
          p {
            color: #fff !important;
            &:nth-of-type(2) {
              font-weight: bold;
            }
          }
        }
      }
    }
    &:deep(.el-tabs__item) {
      font-size: 22px;
      color: #999999;
    }
    &:deep(.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before) {
      content: '' !important;
    }
    &:deep(.el-form-item__label) {
      margin-right: 20px;
    }
    .el-form-item {
      margin-top: 25px;
    }
    .el-input {
      width: 258px;
    }
    &:deep(.el-dialog__title) {
      font-size: 16px;
      font-weight: bold;
    }
    &:deep(.el-icon) {
      font-size: 18px;
    }
    .btn-cancel {
      width: 60px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid rgba(0, 0, 0, 0.15);
      &:hover {
        color: #606266;
      }
    }
    .btn-confirm {
      width: 60px;
      height: 32px;
      background: #1890ff;
      border-radius: 2px;
    }
    .btn-search {
      width: 86px;
      height: 35px;
      background: #1890ff;
      border-radius: 0px 2px 2px 0px;
      margin: 0;
      color: #fff;
      text-align: center;
      line-height: 35px;
      cursor: pointer;
    }
    &:deep(.el-dialog__body) {
      padding: 0;
    }
    &:deep(.el-checkbox__inner) {
      border-radius: 50% !important;
    }
    .dialog {
      height: 330px;
      display: flex;
      &-line {
        height: 1px;
        background: rgba(0, 0, 0, 0.06);
      }
      &-left {
        flex: 1;
        position: relative;
        border-right: 1px solid rgba(0, 0, 0, 0.06);
        &-search {
          display: flex;
          margin-top: 23px;
          align-items: center;
          justify-content: center;
          &:deep(.el-input__wrapper) {
            height: 35px;
          }
          .el-input {
            width: 185px;
          }
        }
        &-list {
          display: flex;
          align-items: center;
          margin: 18px 0 0 34px;
          > span {
            margin-right: 10px;
          }
          .el-icon {
            cursor: pointer;
          }
        }
        &-footer {
          position: absolute;
          bottom: 20px;
          left: 20px;
        }
      }
      &-right {
        flex: 1;
        &-title {
          margin: 31px 0 0 24px;
          font-size: 16px;
          color: #333333;
          font-weight: bold;
        }
        &-list {
          margin-top: 22px;
          height: 220px;
          overflow-y: auto;
          .el-checkbox {
            padding-left: 24px;
          }
          .el-checkbox-group {
            width: 189px;
            height: 36px;
          }
          .is-checked {
            width: 189px;

            background: #dde2ee;
          }
        }
        &:deep(.el-checkbox__label) {
          display: flex;
          align-items: center;
          img {
            margin-left: 15px;
          }
        }
      }
    }
  }
}
</style>
